package com.yuting.server;

import com.yuting.model.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 实现服务器的主功能
 * @author cyt
 * @date 2020/6/28
 */
public class ServerView {


    private ServerInitClose serverInitClose;

    private ServerDao serverDao;

    private StudentManagement studentManagement;

    private QuestionManagement questionManagement;

    public ServerView(ServerInitClose serverInitClose, ServerDao serverDao,StudentManagement studentManagement, QuestionManagement questionManagement){
        this.serverInitClose = serverInitClose;
        this.serverDao = serverDao;
        //初始化学生信息管理，并且从file中读取学生信息
        this.studentManagement = studentManagement;
        studentManagement.readData();
        //初始化考题信息，并且从file中读取考题信息
        this.questionManagement = questionManagement;
        questionManagement.readData();
    }

    /**
     * 实现接收客户端发来的消息并处理回复
     */
    public void serverReceive() throws IOException, ClassNotFoundException {
        while (true){
            //登录信息
            UserMessage um = (UserMessage) serverInitClose.getOis().readObject();
            System.out.println("接收到的消息是："+ um);
            boolean isManager = false;
            //调用serverDao里的方法校验manager
            if(serverDao.serverManagerCheck(um.getUser())){
                um.setType("success");
                isManager = true;
            }else if(studentManagement.studentLogin(Integer.parseInt(um.getUser().getUsername()),um.getUser().getPassword())){
                um.setType("success");
            }else {
                um.setType("fail");
            }

            serverInitClose.getOos().writeObject(um);
            System.out.println("响应为："+um);
            System.out.println("服务器发送信息给客户端成功！");
            if(isManager == true){
                while (true){
                    Object rec = serverInitClose.getOis().readObject();

                    //若是管理学生的信息
                    if(rec instanceof StudentMessage){
                        StudentMessage sm = (StudentMessage)rec;
                        System.out.println("接收到的消息是："+ sm);
                        switch (sm.getType()){
                            case "add":
                                if(studentManagement.add(sm.getStudent())){
                                    sm.setType("success");
                                    System.out.println(sm.getStudent() + "添加成功！");
                                }else {
                                    sm.setType("fail");
                                    System.out.println(sm.getStudent() + "添加失败！");
                                }
                                break;
                            case "delete":
                                if(studentManagement.delete(sm.getStudent())){
                                    sm.setType("success");
                                    System.out.println(sm.getStudent() + "删除成功！");
                                }else {
                                    sm.setType("fail");
                                }

                                break;
                            case "modify":
                                if(studentManagement.modify(sm.getStudent())){
                                    sm.setType("success");
                                    System.out.println(sm.getStudent() + "修改成功！");
                                }else {
                                    sm.setType("fail，there is no this student");
                                    System.out.println("fail，there is no this student");
                                }
                                break;
                            case "search":
                                Student student = studentManagement.search(sm.getStudent());
                                if(student != null){
                                    sm.setStudent(student);
                                    sm.setType("success");
                                    System.out.println(sm.getStudent() + "查询成功！");
                                }else {
                                    sm.setType("fail, there is no this student!");
                                    System.out.println("fail, there is no this student!");
                                }
                                break;


                        }
                        System.out.println(sm.getType());
                        serverInitClose.getOos().writeObject(sm);
                        System.out.println("响应为："+sm);
                        //管理考题
                    }else if(rec instanceof QuestionMessage){
                        QuestionMessage qm = (QuestionMessage)rec;
                        System.out.println("接收到的消息是："+ qm);
                        switch (qm.getType()){
                            case "add":

                                if(questionManagement.add(qm.getQuestion())){
                                    qm.setType("success");
                                    System.out.println(qm.getQuestion() + "添加成功！");
                                }else {
                                    qm.setType("fail");
                                    System.out.println(qm.getQuestion() + "添加失败！");
                                }
                                break;
                            case "delete":
                                if(questionManagement.delete(qm.getQuestion())){
                                    qm.setType("success");
                                    System.out.println(qm.getQuestion() + "删除成功！");
                                }else {
                                    qm.setType("fail");
                                    System.out.println(qm.getQuestion() + "删除失败！");
                                }

                                break;
                            case "modify":
                                if(questionManagement.modify(qm.getQuestion())){
                                    qm.setType("success");
                                    System.out.println(qm.getQuestion() + "修改成功！");
                                }else {
                                    qm.setType("fail");
                                    System.out.println(qm.getQuestion() + "修改失败！");
                                }
                                break;
                            case "search":
                                Question question = questionManagement.search(qm.getQuestion());
                                if(question != null){
                                    qm.setQuestion(question);
                                    qm.setType("success");
                                    System.out.println(qm.getQuestion() + "查询成功！");
                                }else {
                                    qm.setType("fail, there is no this question!");
                                    System.out.println(qm.getQuestion() + "查询失败！");
                                }

                        }
                        serverInitClose.getOos().writeObject(qm);
                        System.out.println("响应为："+qm);
                    }else if(rec instanceof UserMessage){
                        um = (UserMessage)rec;
                        if("exit".equals(um.getType())){
                            break;
                        }
                    }
                }
                //若为学生用户
            }else if("success".equals(um.getType())){
                while (true){
                    StudentFunctionMessage sfm = (StudentFunctionMessage)serverInitClose.getOis().readObject();
                    System.out.println("接收到的信息为："+sfm);
                    int index = 0;
                    int score = 0;
                    Map<Integer, Integer> map = new HashMap<>();
                    switch (sfm.getType()){
                        //开始考试
                        case "start":
                            while (true){

                                //如果题号达到最大，那么提醒学生是否交卷
                                if(index >= questionManagement.numOfQuestion()){
                                    sfm.setType("submit?");
                                    //若没有达到最后一题，则继续向学生放题
                                }else {
                                    sfm.setType("test");
                                    sfm.setQuestion(questionManagement.getByIndex(index).getQuestionNum()+". \r\n"+questionManagement.getByIndex(index).getQuestionContent());
                                    index++;

                                }
                                serverInitClose.getOos().writeObject(sfm);
                                System.out.println("响应为："+sfm);
                                sfm = (StudentFunctionMessage)serverInitClose.getOis().readObject();
                                System.out.println("考试："+sfm);
                                //如果学生交卷，那就把每道题的分加起来算总分并保存
                                if(sfm.getType().equals("submit")){
                                    for (int i : map.values()){
                                        score+=i;
                                    }
                                    studentManagement.assess(Integer.parseInt(um.getUser().getUsername()),score);
                                    sfm.setType("success_submit");
                                    serverInitClose.getOos().writeObject(sfm);
                                    System.out.println("响应为："+sfm);
                                    break;
                                    //如果学生输入题号想重新作答，则发给学生对应的题，然后等待学生的答案
                                }else if(sfm.getType().matches("\\d+")){
                                    int questionNum = Integer.parseInt(sfm.getType());
                                    Question question = questionManagement.getByIndex(questionNum);
                                    if(question != null){
                                        sfm.setQuestion(question.getQuestionContent());

                                    }
                                    serverInitClose.getOos().writeObject(sfm);
                                    System.out.println("响应为："+sfm);
                                    sfm = (StudentFunctionMessage) serverInitClose.getOis().readObject();
                                    System.out.println("接收到的消息是："+ sfm);
                                    //若对则加分，不对0分
                                    if(sfm.getAnswer().equalsIgnoreCase(question.getCorrectAnswer())){
                                        map.put(questionNum,20);
                                    }else {
                                        map.put(questionNum,0);
                                    }
                                    continue;
                                    //若学生在正常答题，检查其正确与否
                                }else if(sfm.getType().equals("answer")){
                                    if(questionManagement.getByIndex(index - 1).getCorrectAnswer().equals(sfm.getAnswer())){
                                        map.put(index - 1,20);
                                    }else {
                                        map.put(index - 1, 0);
                                    }
                                }
                            }
                        break;
                        case "gradeCheck":
                            sfm.setScore(studentManagement.search(new Student(Integer.parseInt(um.getUser().getUsername()))).getScore());
                            serverInitClose.getOos().writeObject(sfm);
                            System.out.println("响应为："+sfm);
                            System.out.println(um.getUser().getUsername()+"查分成功");
                        default:
                    }
                }
            }
        }

    }
}
